# coding='utf-8'

from flask import Flask,render_template,redirect
from flask import url_for,make_response,jsonify
from flask import request,session,abort
import os

app=Flask(__name__)

# obtain secret key from os function
app.secret_key=os.getenv('SECRET_KEY','default_key_by_author')
#配置路由
@app.route('/')
def index():
    # return '<h1> HelloWorld </h1>'
    return render_template('index.html')

@app.route('/demo/hello')
def hello():
    # return" Hello,Flask"  # simple example

    # say hello to the name in cookie
    name=request.args.get('cname')
    if name is None:
        name=request.cookies.get('cname','Machine') #  get value of name from Cookie
        response='<h1>Hello, %s </h1>' %name
    if 'logged_in' in session:
        response +='[Authenticated]'
    else:
        response +='[Not Authenticated]'
    return response

@app.route('/demo/greet/<name>')
def greet(name):
    return "great to see you ,%s" % name

# 配置默认值的
@app.route('/demo/sayhi',defaults={'name':"Newbie"})
@app.route('/demo/sayhi/<name>')
def sayhi(name):
    return '<h2>Hi,%s!</h2>' % name


# 配置监听的HTTP方法
@app.route('/demo/echo',methods=['GET','POST'])
def echo():
    return "<h1> HelloFalsk</h1>"

# 限定输入类型的请求
@app.route('/demo/goback/<int:year>')
def goback(year):
    return "welcome to  %d !" %(2018-year)

#使用any提供有限的访问路径，其他则返回404页面
@app.route('/demo/colors/<any(red,blue,green):color>')
def colors(color):
    return '<p> You made a right choice on color %s</p>' %color

#请求钩子/回调函数 ，用来注册在请求处理的不同阶段执行的处理函数 ，即Callback,且钩子和函数是1v多的

# #请求前运行
# @app.before_request
# def do_something():
#     pass

# #每个请求结束后运行
# @app.after_request
# def after_do():
#     pass

# #每个请求结束后运行
# @app.teardown_request
# def tear():
#     pass

#生成响应 [响应体状态码，首部字段]，本例也是个手动重定向
@app.route('/demo/shitu')
def shitu():
    return '',302,{'Location':'http://so.com'}

#重定向,辅助函数redirect函数,需要引入redirect 
@app.route('/demo/goout')
def goout():
    return redirect('https://www.baidu.com')

#重定向到已有的页面,使用url_for生成目标url路径,注意"()"内是视图函数而非路由路径
@app.route('/demo/meitu')
def meitu():
    print(url_for('sayhi',name='jeep',sex='male',age=98))
    return redirect(url_for('sayhi'))

# 纯文本响应
@app.route('/demo/rtext')
def mime_demo():
     # response=make_response("Hello,Text Response")

    raw_data="Hello ,text response is like this!"
    response=make_response(raw_data)
    response.mimetype='text/plain'
    return response

# xml格式的响应
@app.route('/demo/rxml')
def xml_res():
    raw_data=" <!DOCTYPE html><html><head></head><body><h1>Note</h1><p>to:Peter</p><p>from: Jerry</p><p>body: <strong> Don't forget the party!</strong></p></body></html>"
    response=make_response(raw_data)
    response.mimetype='application/xml'
    return response

# JSON格式的响应
@app.route('/demo/rjson')
def json_res():
    raw_data='{"name":"Terry","age":81}'
    response=make_response(raw_data)
    response.mimetype='application/json'
    return response

# 通过flask自带的jsonify函数自动处理响应格式为json,前提是先引入jsonify这个内置函数
@app.route('/demo/jsonify')
def foo():
    # return jsonify(name="Terry",sex="male")
    return jsonify({"name":"foo_man","age":"105"}),500

# set cookie
@app.route('/demo/set/<name>')
def set_cookie(name):
    response=make_response(redirect(url_for('sayhi')))
    response.set_cookie('cname',name)
    return response

#
@app.route('/demo/login')
def dlogin():
    session['logged_in']=True
    return redirect(url_for('hello'))

@app.route('/demo/admin')
def admin():
    if 'logged_in' not in session:
        abort(403)
    return 'Welcome to admin page'

@app.route('/demo/logout')
def logout():
     if 'logged_in' in session:
        session.pop('logged_in')
     return redirect(url_for('hello'))

#不推荐app.run()的方式，推荐使用flask run --options 命令行模式启动项目
#比如命令行启动 flask run -p 5555 --debug
# if __name__=='__main__':
#     app.run()

@app.route('/getsession')
def showsession():
    return